<?php

namespace app\mini\model;

use app\admin\model\Common;
use app\crm\model\Customer;

class CustomerPointModel extends Common
{
    protected $name = 'customer_point';

    protected $createTime = 'created_at';

    protected $updateTime = 'updated_at';

    protected $autoWriteTimestamp = true;

    /**
     * 积分变动
     *
     * @param $customer_id
     * @param $num
     * @param $type
     * @param $origin
     * @return bool
     */
    static public function pointChange($customer_id, $origin_id,$is_delete=0)
    {
        $point = CustomerPointModel::where([
            ['customer_id', '=', $customer_id],
        ])->find();
        $origin = CustomerPointOriginModel::where('status','=',1)->find($origin_id);
        if(!$origin) {
            return false;
        }
        $type = $origin->change_type;
        if($is_delete!=0) {
            if($type == 1) {
                $type = 2;
            }else{
                $type = 1;
            }
        }
        $num = $origin->num;
        if (empty($point))//新记录
        {
            $point = new CustomerPointModel();
            if ($type == 1) {
                $point->total = $num;
            } else {
                $point->total = 0;
            }
            $point->customer_id = $customer_id;
            if($point->total<0)
            {
                $point->total=0;
            }
            $res = $point->save();
            if (!$res) {
                return false;
            }
        } else {
            if ($type == 1) {
                $point->total += $num;
            } else {
                $point->total -= $num;
            }
            if($point->total<0)
            {
                $point->total=0;
            }
            $res = $point->save();
            if (!$res) {
                return false;
            }
        }
        $log = new CustomerPointLogModel();
        $log->customer_id = $point->customer_id;
        $log->point = $num;
        if($is_delete!=0)
        {
            $log->point = -$num;
        }
        $log->origin_id = $origin_id;
        $res = $log->save();
        if (!$res) {
            return false;
        }
        return true;
    }
}
